using System;
using Slobby.Common.NetworkFormatter;
using System.Reflection;
using System.IO;
using Slobby.SharedNetworkTypes;

namespace Slobby.Client {
    static class Program {
        static Net.ServerConnection b;
        static UI.UserInterface a;

        static ClientReciever rec = new ClientReciever();
        static Common.Dispatcher<ClientReciever> dispatch = new Slobby.Common.Dispatcher<ClientReciever>();

        public static string username;

        public static void OpenBrowser(string url) {
            System.Diagnostics.ProcessStartInfo pstart = new System.Diagnostics.ProcessStartInfo();
            pstart.UseShellExecute = true;
            pstart.FileName = url;
            System.Diagnostics.Process.Start(pstart);
        }

        public static NetworkFormatter NetworkFormatter;

        [STAThread]
        static void Main() {
            NetworkFormatter = new NetworkFormatter(Assembly.Load("SharedNetworkTypes"));

            a = new UI.UserInterface();
            a.LogIn += new EventHandler<Slobby.Client.UI.LogInEventArgs>(a_LogIn);
            a.SendChat += new Action<string>(a_SendChat);
            a.HostGame += new EventHandler(a_HostGame);
            a.Run();
            if (b != null)
                b.Disconnect("Quit");
        }

        static void a_HostGame(object sender, EventArgs e) {
            b.SendMessage(new HostGameMessage(6112));
            Games.SupremeCommander.Host(username);
        }

        static void a_SendChat(string obj) {
            chatRecieved(username, obj);
            b.SendMessage(new SharedNetworkTypes.SendChatMessage(obj));
        }

        static void a_LogIn(object sender, Slobby.Client.UI.LogInEventArgs e) {
            b = new Slobby.Client.Net.ServerConnection();

            b.AuthenticationFailure += AuthenticationFailure;
            b.Authenticated += Authenticated;
            b.Disconnected += Disconnected;
            b.MessageRecieved += MessageRecieved;

            username = e.UserName;
            b.Connect(Properties.ClientSettings.Default.ServerAddress, Properties.ClientSettings.Default.ServerPort , e.UserName, e.PasswordHash);
        }

        static void MessageRecieved(object obj) {
            dispatch.Dispatch(rec, obj);
        }

        public static void chatRecieved (string username, string msg) {
            a.ChatRecieved(username, msg);
        }

        static void Disconnected(string obj) {
            a.Disconnected(obj);
        }

        static void Authenticated(object sender, EventArgs e) {
            a.Connected();
        }

        static void AuthenticationFailure(string obj) {
            a.FailedConnect(obj);
        }
    }
}